﻿using System.Collections.Generic;

namespace dk.Helper.Base.Core
{
    public class Villages : IVillages
    {
        private readonly IVillage[,] values;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object"/> class.
        /// </summary>
        public Villages()
        {
            values = new IVillage[1000,1000];
            VillagesByID = new Dictionary<int, IVillage>();
            VillagesByPlayerID = new Dictionary<int, IList<IVillage>>();
        }

        #region IVillages Members

        /// <summary>
        /// Gets the villages by ID.
        /// </summary>
        public IDictionary<int, IVillage> VillagesByID { get; private set; }

        /// <summary>
        /// Gets the villages by player ID.
        /// </summary>
        public IDictionary<int, IList<IVillage>> VillagesByPlayerID { get; private set; }

        /// <summary>
        /// Gets the villages by coord.
        /// </summary>
        public IVillage[,] VillagesByCoord
        {
            get { return values; }
        }

        /// <summary>
        /// Determines whether this instance contains specified village.
        /// </summary>
        /// <param name="village">The village.</param>
        /// <returns>
        ///   <c>true</c> if this instance contains specified village; otherwise, <c>false</c>.
        /// </returns>
        public bool Contains(IVillage village)
        {
            return this.VillagesByID.ContainsKey(village.ID);
        }

        /// <summary>
        /// Adds the specified village.
        /// </summary>
        /// <param name="village">The village.</param>
        public void Add(IVillage village)
        {
            values[village.Coord.X, village.Coord.Y] = village;

            if (!this.VillagesByID.ContainsKey(village.ID))
                this.VillagesByID.Add(village.ID, village);

            if (!this.VillagesByPlayerID.ContainsKey(village.PlayerID))
                this.VillagesByPlayerID.Add(village.PlayerID, new List<IVillage>());

            if (!this.VillagesByPlayerID[village.PlayerID].Contains(village))
                this.VillagesByPlayerID[village.PlayerID].Add(village);
        }

        /// <summary>
        /// Removes the specified village.
        /// </summary>
        /// <param name="village">The village.</param>
        public void Remove(IVillage village)
        {
            if (!Contains(village))
                return;

            this.VillagesByCoord[village.Coord.X, village.Coord.Y] = null;
            this.VillagesByID.Remove(village.ID);
            this.VillagesByPlayerID[village.PlayerID].Remove(village);
        }

        #endregion
    }
}